from django.shortcuts import render, redirect, HttpResponse
from app import models

# Create your views here.


def index(request):
    return render(request, template_name='index.html')


def home(request):
    return redirect('index')


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        hobby = request.POST.get('hobby')  # 只能获取列表最后一个元素,获取列表用getlist
        hobbies = request.POST.getlist('hobby')
        print(username, password)

        print(request.POST)
        print(hobbies, type(hobbies))
        print(hobby, type(hobby))  # 333 <class 'str'>,get只会获取列表的最后一个元素
        res = models.User.objects.filter(username=username)  # [数据对象]
        user_obj = res.first()
        print('res:', res)
        print(user_obj)
        print(user_obj.password)
        if user_obj:
            if password == user_obj.password:
                return HttpResponse('登录成功')
            return HttpResponse('密码错误')
        else:
            return HttpResponse('用户不存在')
    return render(request, 'login.html')


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        res = models.User.objects.create(username=username, password=password, age=18)
        # 返回创建对象本身
        print(res)

        # 实例化对象创建
        user_obj = models.User(username='AKW', password='FW249746', age=18)
        user_obj.save()
        return HttpResponse(res)
    return render(request, 'register.html')


def userlist(request):
    users = models.User.objects.all()
    data = models.User.objects.filter()
    print(users, list(users))
    print(data)
    print('locals:', locals())
    return render(request, 'usrlist.html', {'users': users})


def edit(request):
    edit_id = request.GET.get('id')

    if request.method == 'POST':
        user_dic = {
            'username': request.POST.get('username'),
            'age': request.POST.get('age'),
            'password': request.POST.get('password')
        }
        print(edit_id)
        user = models.User.objects.filter(id=edit_id)
        users = models.User.objects.get(id=edit_id)
        print('user', user, users)
        user.update(**user_dic)  # filter拿到的是多个对象,执行update会批量更新,用主键会

        # 第二种更新方法
        # users.username = username
        # users.password = password
        # users.save()  效率非常低，会把所有的字段都会改一遍，无论有没有改
        return redirect('userlist')
    user_obj = models.User.objects.get(id=edit_id)
    return render(request, 'edit_user.html', locals())


def delete(request, id):
    models.User.objects.filter(id=id).delete()
    return redirect('userlist')